package com.xiia.admin.servlet;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xiia.common.servlet.FrameworkServlet;
import com.xiia.servcie.imp.PublishService;
import com.xiia.service.inter.IPublish;
import com.xiia.util.CheckConstant;
import com.xiia.util.Pager;
import com.xiia.util.ParamUtil;
import com.xiia.vo.Publish;
import com.xiia.vo.User;

/**
 * 
 * @author meigang 2014-11-10 17:48
 *
 */
@WebServlet("/publish.do")
public class PublishServlet extends FrameworkServlet{
	private static IPublish iPublish;
	private static Pager page;
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public PublishServlet(){
		iPublish = new PublishService();
		page = new Pager();
	}
	
	/**
	 * 查看发布信息
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String listAll(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		int currentPage=1;
		if(request.getParameter("currentPage")!=null){
			currentPage=Integer.parseInt(request.getParameter("currentPage").toString());
		}
		//得到的总行数
		int totalCount=iPublish.count();
		page.paging(currentPage, ParamUtil.PUBLISH_ALL_PAGE_SIZE, totalCount);
		page =iPublish.findAllPublishPage(page,"type");
		request.setAttribute("page",page);

		return "bclient/check/publishList.jsp";
	}
	/**
	 * 发布
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String publish(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Publish p = doForm(request);
		p.setLastPublishTime(new Date());
		p.setUser((User) request.getSession().getAttribute(ParamUtil.LOGIN_USER));
		p.setFlag(CheckConstant.FLAG_YES_PUBLISH);
		if(iPublish.publish(p)){
			resString = "发布成功";
		}else{
			resString = "发布失败";
		}
		request.setAttribute("resString", resString);
		return "check.do?action=list&type="+p.getType();
	}
	/**
	 * 封装表单
	 * @param r
	 * @return
	 */
	private Publish doForm(HttpServletRequest r){
		Publish p = new Publish();
		if(null != r.getParameter("publishedId"))
			p.setPublishedId(Integer.parseInt(r.getParameter("publishedId").trim()));
		if(null != r.getParameter("type"))
			p.setType(r.getParameter("type"));
		
		return p;
	}
}
